package xmysql

import (
	"database/sql"
	"fmt"
	"server/dbtools/sql_db"
)

func GetTbLen(conn *sql.DB, schemaTb string) (tbLen int, err error) {
	if conn == nil || schemaTb == "" {
		return 0, fmt.Errorf("xmysql.GetTbLen():入口参数错误,--conn:%v --schemaTb:%s", conn, schemaTb)
	}

	sqlLen := fmt.Sprintf("select count(*) from %s;", schemaTb)
	rows, err := conn.Query(sqlLen)
	if err != nil {
		return 0, fmt.Errorf("获取表行数失败,\n--err:%v\n --sql:%s\n", err, sqlLen)
	}

	for rows.Next() {
		err = rows.Scan(&tbLen)
		if err != nil {
			return 0, fmt.Errorf("解析表%s行数失败:%v\n", schemaTb, err)
		}
	}

	return tbLen, nil
}

func GetColArray(conn *sql.DB, schemaTb string, colName string, scopeString string) ([]any, error) {
	var colArray = make([]interface{}, 0)
	if conn == nil || schemaTb == "" || colName == "" {
		return colArray, fmt.Errorf("xmysql.GetTbLen():入口参数错误,--conn:%v,--schemaTb:%s,--colName:%s", conn, schemaTb, colName)
	}
	var sql string
	if scopeString != "" {
		sql = fmt.Sprintf("select %s from %s where %s", colName, schemaTb, scopeString)
	} else {
		sql = fmt.Sprintf("select %s from %s", colName, schemaTb)
	}

	rows, err := conn.Query(sql)
	if err != nil {
		return colArray, err
	}

	var v string
	for rows.Next() {
		err = rows.Scan(&v)
		if err != nil {
			return colArray, err
		}
		colArray = append(colArray, v)
	}

	return colArray, nil
}


func GetMysqlSchemaList(mysqlDb *sql.DB) ([]string, error) {
	sqlDbStr := "SELECT SCHEMA_NAME AS `dbName` FROM INFORMATION_SCHEMA.SCHEMATA;"
	rows, err := mysqlDb.Query(sqlDbStr)
	if err != nil {
		return nil, err
	}
	var schemaList = make([]string, 0)
	var schemaName string
	for rows.Next() {
		err := rows.Scan(&schemaName)
		if err != nil {
			fmt.Printf("scan failed, err:%v\n", err)
			return nil, err
		}
		schemaList = append(schemaList, schemaName)
	}
	return schemaList, nil
}


func GetMysqlTbList(mysqlDb *sql.DB, schemaName string) ([]string, error) {
	sqlTbStr := fmt.Sprintf("select TABLE_NAME AS `tbName` from information_schema.tables where table_schema='%s';", schemaName)
	query, err := mysqlDb.Query(sqlTbStr)
	if err != nil {
		return nil, err
	}
	var tbList = make([]string, 0)
	var tbName string
	for query.Next() {
		err := query.Scan(&tbName)
		if err != nil {
			fmt.Printf("scan failed, err:%v\n", err)
			return nil, err
		}
		tbList = append(tbList, tbName)
	}
	return tbList, nil
}

func MysqlTbExist(db *sql.DB, tbName string) (bool, error) {
	sqlCheck := fmt.Sprintf("SHOW TABLES LIKE '%s'", tbName)
	querySql, err := sql_db.QuerySql(db, sqlCheck)
	if err != nil {
		return false, err
	}
	if len(querySql) > 0 {
		return true, nil
	} else {
		return false, err
	}
}
